<?php
/**
 * Poup to Create a new Patient
 * Display a form with patient required fields.
 *
 * @author Xavier VILAIN
 * @package Nawa\MedicalStudy\MedicalCenter\Patient
 * @license
 *
 */

use Fox\Core\Errors;
use Fox\Dao\SqlFragment;
use Fox\Generator;
use Nawa\MedicalStudy\MedicalCenter\Patient;
use Nawa\MedicalStudy\MedicalCenter\Patient\Status;
use Fox\Popup;
use Fox\Html\DropList,Fox\Html\Input;
use Fox\Html\Block;
use Fox\Html\Screen;

$xview = Xview::instance();
$msid = $xview->val('msid');
$mcid = $xview->val('mcid');
$patientid= $xview->val('patientid');
try {
	$patient = Fox\Dao::load(Patient::className(),$msid.':'.$mcid.':'.$patientid);
	$data = $patient->getData();
} catch(Fox\Object\Exception\NotExist $e) {
	
	exit;
}

$screen = new Screen('sAddPatient','update',null,true,
Generator::ajaxReload('MC_patients'));
$block = $xview->component('medicalstudies','patientBlock');
$screen->add($block);
$screen->initialize($data);

if($screen->submitted())
{
	$fields = $screen->get();
	if(!$screen->errors()) {
		// Compare Selection Date VS Inclusion Date
		if(!empty($fields['selection_date']) && !empty($fields['inclusion_date'])) {
			if($fields['selection_date'] > $fields['inclusion_date']) {
				Fox\Message::Error(Msg(Nawa\Messages::BUNDLE,Nawa\Messages::ERR_X_LOWER_THAN_Y,
					$block->item('selection_date')->label(),
					$block->item('inclusion_date')->label()));
			}
		}
	}
	
	if(!$screen->errors())
	{
		try {
			
			
			$patient->setFields($fields);
			$patient->update();
			Fox\Message::Success(Msg(Nawa\Messages::BUNDLE,
									Nawa\Messages::PATIENT_UPDATED,
									$fields['reference']));
			
		}
		catch (Fox\Object\Exception\Save $e)
		{
			Fox\Message::Error($e);
		}
	}
	echo $xview->messages(true,true);
	exit;
}
$popup = new Popup('pAddPatient',Msg(Nawa\Messages::BUNDLE,Nawa\Messages::PATIENT_ADD_TITLE),$screen);
if($screen->errors())
{
	echo Xview::instance()->messages();
}
else
{
	echo $popup->display();
}